<template>
  <div class="ui-panle" style="position:relative">
    <code-editer @codeEditorInit="codeEditorInit" @saveFileChange="getFileList(filepathStr)"></code-editer>
    <div class="file-path">
      <div id="file-breadcrumb" style="flex:1">
        <Select v-model="serverListSelect" :datas="serverListData" @change="serverListChange" type="Object" :no-border="true" :equal-width="false" :null-option="false" placeholder="选择服务器">
          <template slot-scope="{item}" slot="item">
            <div class="primary-color" style="padding:5px 0;"><b>{{item.title}}</b><span style="float:right;width:220px;text-align:right" class='gray1-color text-ellipsis'>{{item.hostname}}</span>
            </div>
            <div class='gray1-color' style="border-top:dashed 1px rgba(0,0,0,0.1)">{{item.guid}}</div>
          </template>
        </Select>
        <div id="file-breadcrumb-item">
          <span><i :class="isFileLoading?'h-icon-loading':'fas fa-desktop'"></i></span>
        </div>
        <div id="file-breadcrumb-item" @click="getFileList(filepathStr)" v-if="serverListSelect!=null">
          <span><i class="fas fa-redo"></i>&nbsp;&nbsp;刷新</span>
          <!-- &nbsp;&nbsp;<i class="el-icon-arrow-right"></i> -->
        </div>
        <div style="padding:0 10px;" v-if="serverListSelect!=null && isInstallPlugIn && fileManageMode=='install'">
          <button style="height:35px" class="h-btn h-btn-s h-btn-primary" @click="$refs.upfile.click()"><i class="fas fa-cloud-upload-alt"></i>&nbsp;&nbsp;上传自定义插件</button>
          <input type="file" name="file" style="display:none;" ref="upfile" @change="upfileChange">
          &nbsp;&nbsp;<span v-if="upfileLoading" class="yellow-color"><i class="h-icon-loading"></i>&nbsp;&nbsp;上传中...请勿切换界面</span>
        </div>
        <!-- <div id="file-breadcrumb-item" v-show="false">
          <span>插件列表</span>
        </div> -->
      </div>
      <SwitchList style="float-right" v-model="fileManageMode" :datas="[{key:'install',title:'已安装',icon:'fas fa-cube'},{key:'cloud',title:'云插件',icon:'fas fa-cloud'}]"></SwitchList>
    </div>
    <div class="file-panle">
      <div style="padding:10px;" v-if="serverListSelect!=null && !isInstallPlugIn">
        <span class="h-tag h-tag-yellow">该服务器还没有安装插件框架，请前往【服务器列表】安装插件框架后再试</span>
      </div>

      <div class="file-list-box" v-if="serverListSelect!=null && isInstallPlugIn" :style="{height: fileManageMode=='install'?'calc(100% - 100px)':'calc(100% - 50px)'}">
        <div v-show="fileManageMode=='install'" style="padding:10px 20px;">
          <!-- <div>搜索插件名：</div> -->
          <div class="h-input h-input-prefix-icon" style="position:relative">
            <input type="text" v-width="300" v-model="pluginSeachValue" placeholder="输入关键词查询" @input="pluginSeachInput" style="padding-right:30px;"/>
            <i class="h-icon-search"></i>
            <div style="padding:0 10px;position:absolute;right:0px;top:5px;z-index:10;cursor:pointer" v-show="pluginSeachValue" @click="pluginSeachValue=''">
              <i class="h-icon-close"></i>
            </div>
          </div>

        </div>
        <Table v-show="fileManageMode=='install'" :datas="sortFileData" :checkbox="true" @select="fileTableSelect" :loading="isFileLoading">
          <TableItem title="插件名" prop="auto">
            <template slot-scope="{data}">
              <div id="file" v-if="data.isFile">
                <i class="fas fa-cube"></i>
                &nbsp;&nbsp;<span class="text-ellipsis" style="font-weight:bold">{{data.name.replace('.cs','')}}</span>
                &nbsp;&nbsp;<span class="h-tag h-tag-bg-primary" v-if="(new Date().getTime()-data.time)<1000*60*10">新</span>
              </div>
            </template>
          </TableItem>
          <TableItem title="插件大小" align="center" prop="size" sort="auto" :format="(v)=>{return toSize(v)}">
            <!-- <template slot-scope="{data}">
              <span>{{toSize(data.size)}}</span>
            </template> -->
          </TableItem>
          <TableItem title="最后修改时间" prop="time" sort="auto" :format="(v)=>{return new Date(v).format('yyyy/MM/dd hh:mm:ss')}">
            <!-- <template slot-scope="{data}">
              <span>{{new Date(data.time).format('yyyy/MM/dd hh:mm:ss')}}</span>
            </template> -->
          </TableItem>
          <TableItem title="操作" :width="150">
            <template slot-scope="{data}">
              <button class="h-btn h-btn-s h-btn-primary" style="height:30px;" :disabled="!data.isFile" @click="readfile(data)"><i class="fas fa-edit"></i></button>&nbsp;&nbsp;
              <Poptip content="是否删除该插件？" @confirm="removeOneFiles(data.path)">
                <button style="height:30px;" class="h-btn h-btn-s h-btn-red"><i class="h-icon-trash"></i><span>删除</span></button>
              </Poptip>
            </template>
          </TableItem>
          <div slot="empty">没有任何插件</div>
        </Table>
        <Table v-show="fileManageMode!='install'" :datas="sortcloudPlugData" :checkbox="true" :loading="isFileLoading">
          <TableItem title="插件名">
            <template slot-scope="{data}">
              <div id="file" v-if="data.isFile">
                <i class="fas fa-cloud"></i>
                &nbsp;&nbsp;<span class="text-ellipsis" style="font-weight:bold">{{data.name.replace('.cs','')}}</span>
                &nbsp;&nbsp;<span class="h-tag h-tag-bg-primary" v-if="(new Date().getTime()-data.time)<1000*60*10">新</span>
              </div>
            </template>
          </TableItem>
          <TableItem title="备注" align="center">
            <template slot-scope="{data}">
              <span class="yellow-color text-ellipsis" style="font-size:12px;">{{data.des}}</span>
            </template>
          </TableItem>
          <TableItem title="安装状态" align="center" :width="100">
            <template slot-scope="{data}">
              <span class="h-tag h-tag-bg-primary text-ellipsis" style="font-weight:bold" v-if="data.isInstall">已安装</span>
              <span class="h-tag h-tag-bg-gray text-ellipsis" style="font-weight:bold" v-else>未安装</span>
            </template>
          </TableItem>
          <TableItem title="插件大小" :width="120" align="center">
            <template slot-scope="{data}">
              <span>{{toSize(data.size)}}</span>
            </template>
          </TableItem>
          <TableItem title="最后修改时间" :width="150">
            <template slot-scope="{data}">
              <span>{{new Date(data.time).format('yyyy/MM/dd hh:mm:ss')}}</span>
            </template>
          </TableItem>
          <TableItem title="操作" :width="150">
            <template slot-scope="{data}">
              <button style="height:30px;" class="h-btn h-btn-s h-btn-primary" :class="{'h-btn-loading':data.isLoading}" v-if="!data.isInstall" @click="installPlugin(data)">
                <i :class="data.isLoading?'h-icon-spinner':'fas fa-plus'"></i><span>安装</span>
              </button>
              <button style="height:30px;" class="h-btn h-btn-s h-btn-blue" :class="{'h-btn-loading':data.isLoading}" v-else @click="installPlugin(data)"><i
                  :class="data.isLoading?'h-icon-spinner':'h-icon-refresh'"></i><span>重装</span></button>
            </template>
          </TableItem>
          <div slot="empty">没有任何插件</div>
        </Table>
        <div class="file-toolbar">
          <div class="item" style="font-size:12px">
            {{fileManageMode=='install'?fileData.length:cloudPlugData.length}} 个插件
          </div>
          <div class="item" id="remove" v-if="selectTableData.length>0">
            <Poptip content="是否删除选中的所有插件？" @confirm="removeFiles" v-if="fileManageMode=='install'">
              <button style="height:30px;" class="h-btn h-btn-s h-btn-red"><i class="h-icon-trash"></i><span>批量删除插件</span></button>
            </Poptip>
          </div>
        </div>
      </div>
    </div>
    <Loading text="Loading" :loading="readfileLoading"></Loading>
  </div>
</template>

<script>
export default {
  data() {
    return {
      pluginSeachValue: '',
      upfileLoading: false,
      isInstallPlugIn: false,
      readfileLoading: false,
      serverListSelect: null,
      serverListData: [],
      fileManageMode: 'install',
      editor: null,
      filepath: [],
      fileData: [],
      isFileLoading: false,
      selectTableData: [],
      cloudPlugData: [],
      filterFileData: [],
    }
  },
  watch: {
    filepathStr(val) {
      this.getFileList(val)
    }
  },
  computed: {
    filepathStr() {
      return ('/' + this.filepath.join('/') + '/').replace(/\/+/g, '/')
    },
    sortFileData() {
      let s = this.fileData
      s.sort((a, b) => {
        let filenamea = a.name.toLowerCase().charCodeAt(0)
        let filenameb = b.name.toLowerCase().charCodeAt(0)

        return filenamea - filenameb
      })
      return this.pluginSeachValue != '' ? this.filterFileData : s
    },
    sortcloudPlugData() {
      let s = this.cloudPlugData
      s.sort((a, b) => {
        let filenamea = a.name.toLowerCase().charCodeAt(0)
        let filenameb = b.name.toLowerCase().charCodeAt(0)
        // return b.time - a.time
        return filenamea - filenameb
      })
      return s
    }
  },
  mounted: function () {
    this.getServerList()
    // this.getFileList(this.filepathStr)
  },
  methods: {
    pluginSeachInput() {
      this.filterFileData = this.fileData.filter((e) => {
        return e.name.toLowerCase().replace('.cs', '').indexOf(this.pluginSeachValue.toLowerCase()) != -1
      })
      // console.log(a)
    },
    async upfileChange(e) {
      if (this.$refs.upfile.files.length <= 0) { return }
      this.upfileLoading = true
      let ret = await this.$file.upfileplug(this.$refs.upfile.files[0])
      if (ret.code < 0) {
        this.$Notice({
          type: 'error',
          title: '错误',
          content: ret.msg
        });
        this.upfileLoading = false
        return
      } else {
        this.$Notice({
          type: 'success',
          title: '成功',
          content: '上传插件安装成功'
        });
        this.getFileList(this.filepathStr)
      }
      this.$refs.upfile.value = ''
      this.upfileLoading = false
      // console.log(this.$refs.upfile.files[0])
    },
    async getCloudPlugList() {
      let ret = await this.$file.cloudpluglist()
      this.cloudPlugData = ret.files.map((item) => {
        let isInstall = this.fileData.filter((item2) => {
          return item2.name == item.name
        })
        item.isLoading = false
        item.isInstall = isInstall.length > 0 ? true : false
        return item
      })
    },
    serverListChange(data) {
      this.$file.setPort(data.key)
      this.getFileList('')
    },
    async installPlugin(data) {
      data.isLoading = true
      let ret = await this.$file.installplugin(data.name)
      if (ret.code < 0) {
        this.$Message({
          type: 'error',
          text: ret.msg
        });
        data.isLoading = false
        return
      } else {
        data.isInstall = true
        this.$Message({
          type: 'success',
          text: '插件安装成功'
        });
        this.getFileList(this.filepathStr)
      }
      data.isLoading = false
    },
    async removeOneFiles(data) {
      this.isFileLoading = true
      let ret = await this.$file.delplugin([data])
      if (ret.code < 0) {
        this.$Notice({
          type: 'error',
          title: '错误',
          content: ret.msg
        });
        this.isFileLoading = false
        return
      } else {
        this.$Notice({
          type: 'success',
          title: '成功',
          content: '删除插件成功'
        });
        this.getFileList(this.filepathStr)
      }
      this.isFileLoading = false
    },
    async removeFiles() {
      this.isFileLoading = true
      let ret = await this.$file.delplugin(this.selectTableData)
      if (ret.code < 0) {
        this.$Notice({
          type: 'error',
          title: '错误',
          content: ret.msg
        });
        this.isFileLoading = false
        return
      } else {
        this.$Notice({
          type: 'success',
          title: '成功',
          content: '已删除所选插件'
        });
        this.getFileList(this.filepathStr)
      }
      this.isFileLoading = false
    },
    fileTableSelect(e) {
      //console.log(e)
      this.selectTableData = e.map((item) => {
        return item.path
      })
    },
    codeEditorInit(editor) {
      //   console.log('编辑器初始化完成')
      this.editor = editor
    },
    async getServerList() {
      let ret = await this.$API.getserver()
      this.serverListData = ret.map((item, index) => {
        return {
          title: '#' + (index + 1),
          hostname: item.configinfo.server_hostname,
          key: parseInt(item.server_port),
          guid: item.server_guid,
          rcon: {
            port: item.configinfo.rcon_port,
            password: item.configinfo.rcon_password
          }
        }
      })
    },
    toSize(size) {
      size = Number(size)
      let unit = ['B', 'KB', 'MB', 'GB']
      for (let i = 0, step = 1; i < unit.length; i++) {
        //console.log(size / step, size, step, unit[i], i)
        if (size / step < step) {
          return (size / step).toFixed(2) + ' ' + unit[i]
        }
        step *= 1024
      }
    },
    async readfile(item) {
      item.path = item.path.replace('.cs', '.json')
      if (item.isFile) {
        this.readfileLoading = true
        this.editor.openFile('/oxide/config/' + item.path, this.serverListSelect).then(isLoading => {
          this.readfileLoading = false
        })
      }


    },
    // async readfile(item) {
    //   this.isFileLoading = true
    //   let ret = await this.$file.verifyfile(this.filepathStr + item.path)
    //   if (ret.code == -1) {
    //     this.$Notice({
    //       type: 'error',
    //       title: '错误',
    //       content: ret.msg
    //     });
    //     this.isFileLoading = false
    //     return
    //   }
    //   ret = await this.$file.readfile(this.filepathStr + item.path)
    //   this.editor = ret
    //   this.isFileLoading = false
    //   //this.randomkey = this.createRamdomKey()
    // },
    changePath(index) {
      //console.log(this.filepath.slice(0, index + 1))
      this.filepath = this.filepath.slice(0, index + 1)
      //   this.getFileList(this.filepathStr)
    },
    async getFileList(path) {
      this.isFileLoading = true
      let ret = await this.$file.pluginlist()
      if (ret.code < 0) {
        this.isInstallPlugIn = false
        this.isFileLoading = false
        return
      }
      this.fileData = ret.files
      this.getCloudPlugList()
      this.isFileLoading = false
      this.isInstallPlugIn = true
      //console.log(this.fileData)

    }
  }
}
</script>
<style lang="less" scoped>
#file-breadcrumb {
  padding-right: 2px;
  display: flex;
  align-items: center;
  #file-breadcrumb-item {
    text-align: center;
    position: relative;
    cursor: pointer;
    // height: 20px;
    // min-width: 30px;
    margin: 0 1px;
    font-size: 14px;
    display: flex;
    justify-content: center;
    align-items: center;
    border-radius: 3px;
    padding: 8px 10px;
    // font-weight: bold;
    color: rgb(45, 173, 143);
    flex-wrap: wrap;
    background: #caf5eb;
    &:hover {
      background: rgba(47, 218, 178, 0.4);
    }
    // &:last-child {
    //   // flex: 1;
    //   &:hover {
    //     background: #caf5eb;
    //   }
    //   // cursor: default;
    // }
  }
}
/deep/ .h-switchlist > span {
  padding: 10px;
}
.file-path {
  display: inline-block;
  padding: 10px;
  display: flex;
  align-items: center;
}
.file-panle {
  //   padding: 10px;
  //   margin-bottom: 20px;
  height: calc(100% - 60px);
  overflow: hidden;
  overflow-y: auto;
  //   border-top: solid 1px rgba(0, 0, 0, 0.08);
}

.file-list-box {
  .file-toolbar {
    height: 50px;
    padding: 7px 0;
    padding-bottom: 0;
    display: flex;
    align-items: center;
    .item {
      &:first-child {
        flex: 1;
      }
      display: flex;
      //   height: 100%;
      //   padding: 7px 0;
    }
  }
  height: calc(100% - 100px);
  /deep/ .h-table {
    height: 100%;
  }
  /deep/ .h-table-container {
    height: calc(100% - 50px);
    overflow: hidden;
    overflow-y: auto;
  }
  //   /deep/ tr {
  //     cursor: pointer;
  //   }
  /deep/ td div#file {
    // cursor: pointer;
    display: flex;
    align-items: center;
    // align-self: center;
    // padding: 0 10px;
    font-size: 1.1em;
    img {
      font-size: 1em;
    }
    i {
      font-size: 1.4em;
    }
  }
}
</style>
